package com.xxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Code;
import com.xxx.common.Result;
import com.xxx.entity.User;
import com.xxx.entity.dto.UserDto;
import com.xxx.exception.BusinessException;
import com.xxx.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xxx
 * @since 2024-11-23
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/add")
    @Operation(summary = "添加用户")
    public Result add(@RequestBody User user){
        Boolean flag = userService.save(user);
        return flag ? Result.success("添加用户成功") : Result.error("添加用户失败");
    }

    @GetMapping("/delete/{userId}")
    @Operation(summary = "删除用户")
    public Result delete(@PathVariable Integer userId){
        Boolean flag = userService.removeById(userId);
        return flag ? Result.success("删除用户成功") : Result.error("不存在该用户Id");
    }

    @PutMapping("/update")
    @Operation(summary = "修改用户")
    public Result update(@RequestBody User user){
        Boolean flag = userService.updateById(user);
        return flag ? Result.success("修改用户成功") : Result.error("修改用户失败");
    }

    @GetMapping("/selectByPage/{current}/{size}")
    @Operation(summary = "分页查询用户")
    public Result selectByPage(@PathVariable Integer current, @PathVariable Integer size){
        IPage<User> page = userService.page(new Page<>(current,size));
        return Result.success(page);
    }

    @PostMapping("/selectByCondition")
    @Operation(summary = "根据用户名、用户电话、用户Id条件查询用户")
    public Result selectByCondition(@RequestBody UserDto userDto){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.like(userDto.getUserName()!=null&&!userDto.getUserName().equals(""),
                        User::getUserName,userDto.getUserName())
                .eq(userDto.getUserPhone()!=null&&!userDto.getUserPhone().equals(""),
                        User::getUserPhone,userDto.getUserPhone())
                .eq(userDto.getUserType()!=null&&!userDto.getUserType().equals(""),
                        User::getUserType,userDto.getUserType())
                .eq(userDto.getUserId()!=null,User::getUserId,userDto.getUserId());
        IPage<User> page = userService.page(new Page<>(userDto.getCurrent(), userDto.getSize()),
                lqw);
        return Result.success(page);
    }
}

